package com.swift.violent.mainstay.config.expand;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.alenfive.rocketapi.config.QLRequestMappingFactory;
import com.github.alenfive.rocketapi.config.SpringContextUtils;
import com.github.alenfive.rocketapi.entity.ApiInfo;
import com.github.alenfive.rocketapi.extend.IResultWrapper;
import com.swift.violent.mainstay.common.constants.Global;
import com.swift.violent.mainstay.common.lang.CommonResultOutput;
import com.swift.violent.mainstay.log.service.LogSyncService;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 默认结果包装类
 *
 * @author xuhaifeng
 * @date 2021.1.19 21:12
 */
@Component
public class DefaultResultWrapper implements IResultWrapper {

    @SneakyThrows
    private ApiInfo apiInfo(HttpServletRequest request) {
        final QLRequestMappingFactory mappingFactory = SpringContextUtils.getApplicationContext().getBean(QLRequestMappingFactory.class);
        final String pattern = mappingFactory.buildPattern(request);
        if (Objects.isNull(pattern)) {
            return null;
        }
        return mappingFactory.getPathList(false).stream().filter(item -> pattern.equals(item.getPath()) && (request.getMethod().equals(item.getMethod()) || "ALL".equals(item.getMethod()))).findFirst().orElse(null);
    }

    @Override
    public Object wrapper(Object data, HttpServletRequest request, HttpServletResponse response) {
        if (Global.NUM_1.equals(DefaultApiInfoInterceptor.rySecurityFunctionStatus())) {
            final ApiInfo apiInfo = apiInfo(request);
            final JSONObject jsonObject = JSON.parseObject(Objects.requireNonNull(apiInfo).getOptions());
            if (jsonObject.containsKey(Global.LOG)) {
                LogSyncService.handleLog(apiInfo.getName(), jsonObject.getString(Global.LOG), data, apiInfo.getPath(), null, request);
            }
        }
        return CommonResultOutput.commonSuccessOutput(data);
    }

    @Override
    public Object throwable(Throwable throwable, HttpServletRequest request, HttpServletResponse response) {
        if (Global.NUM_1.equals(DefaultApiInfoInterceptor.rySecurityFunctionStatus())) {
            final ApiInfo apiInfo = apiInfo(request);
            final JSONObject jsonObject = JSON.parseObject(Objects.requireNonNull(apiInfo).getOptions());
            if (jsonObject.containsKey(Global.LOG)) {
                LogSyncService.handleLog(apiInfo.getName(), jsonObject.getString(Global.LOG), Global.NOT, apiInfo.getPath(), throwable, request);
            }
        }
        return CommonResultOutput.commonErrorOutput(response.getStatus(), String.valueOf(throwable.getCause()));
    }

}
